<?php

header("Content-Type: text/html; charset=iso-8859-1");

// Framework Path
define('APP_FRAMEWORK')		or define('APP_FRAMEWORK', dirname(__FILE__));

class App{
	
	const C_Ctrl 	= 'path_ctrl';
	const C_Flow 	= 'path_flow';
	const C_Enum 	= 'path_enum';
	const C_View 	= 'path_view';
	const C_Model 	= 'path_model';
	const C_Layout 	= 'path_layout';
	
	/**
	 * Request realizado a la pagina
	 * @var CRequest
	 */
	public static $Request;
	/**
	 * Response que realizara la pagina
	 * @var CResponse
	 */
	public static $Response;
	/**
	 * Path donde esta ejecutandoze el framework
	 */
	public static $AppPath;
	
	//Trigger de registro de clases de autoload
	private static function registerAutoloader(){
		spl_autoload_register(array("App", "autoload"));	
	}
	
	//Carga de clases de framework o controladoras de applicacion.
	//No carga entidades ni vistas, es responsabilidad de las controladoras.
	public static function autoload($className, $ctrl=false){
		//Carga clase de framework
		if($ctrl==false){
			if(isset(App::$_coreClasses[$className])){
				include_once (APP_FRAMEWORK.self::$_coreClasses[$className]);
				Log::Write("ClassLoader:Framework ".APP_FRAMEWORK.self::$_coreClasses[$className]." - OK");
			}else{
				Debug::Write("ClassLoader:Framework $className no existe");
			}
		}else{
			$filename = APP_PATH.Config::$opt['app']['path_ctrl'];
			$filename.= 'ctrl_'.strtolower(substr($className, 1)).'.php';
			if(file_exists($filename)){
				Log::Write("ClassLoader:Control ".$filename." - OK");
				include_once($filename);
			}else{
				Debug::Write("ClassLoader:Control $className no existe.");
			}
		}
	}
	
	public static function getVersion(){
		return 'Beta 1.0';
	}
	
	private static function configWebApp($config){
		include_once($config);
		Log::Write("App:LoadingConfiguration $config");
	}
	
	public static function run($config){
		App::configWebApp($config);
		
		Log::Write("App:Start version-".self::getVersion());
		session_start(); //Inicializa manejador de sesion
		
		App::$Request = new CRequest();
		App::$Response = new CResponse();
		App::$AppPath = APP_PATH;
		
		App::loadEnums(); //Carga todas las enumeraciones
		
		App::registerAutoloader();
		App::executeRequest();
		
		//Finaliza el render en caso de que no fue llamado por nadie
		App::$Response->render();
	}

	public static function getIncludeFile($type, $filename){
		return APP_PATH.Config::$opt['app'][$type].$filename;
	}
	
	public static function includeFile($type, $filename){
		include_once self::getIncludeFile($type, $filename);
	}
	
	//Configura cadena de ejecucion
	private static function executeRequest(){
		App::$Request->_command = isset($_GET['kn_ctrl']) ? $_GET['kn_ctrl'] : Config::$opt['app']['base_command'];; //Controladora
		App::$Request->_action = isset($_GET['kn_actn']) ? $_GET['kn_actn'] : Config::$opt['app']['base_action']; //Accion
		
		App::$Request->_layout = isset($_GET['kn_nmly']) ? $_GET['kn_nmly'] : Config::$opt['view']['base_layout']; //Nombre de layout
		
		App::autoload(App::$Request->_command, true);

		//Valida comando
		if(App::$Request->_command == false || class_exists(App::$Request->_command) == false)
		{ Debug::Write("Error 404 - No se envio un comando valido."); die(); }
		
		$comand = new App::$Request->_command();
		$comand->invoke(App::$Request->_action);	
	}
	
	private static function loadEnums(){
		if ($handle = opendir(APP_PATH.Config::$opt['app']['path_enum'])) {
			while (false !== ($file = readdir($handle)))
			{
				if ($file != "." && $file != "..")
				{ App::includeFile(App::C_Enum, $file); }
			}
			closedir($handle);
		}	
	}
	
	//Lista de clases de framework
	private static $_coreClasses=array(
		'Debug'				=> '/console/Debug.php',
		'Warning'			=> '/console/Warning.php',
		'Log'				=> '/console/Log.php',
		'CPage'				=> '/base/CPage.php',
		'CBaseModel'		=> '/base/CBaseModel.php',
		'CModelField'		=> '/base/CModelField.php',
		'CBaseController'	=> '/base/CBaseController.php',
		'CRequest'			=> '/base/CRequest.php',
		'CResponse'			=> '/base/CResponse.php',
		'CViewRender'		=> '/base/CViewRender.php',
		'CBaseFlow'			=> '/base/CBaseFlow.php',
		'CFieldTag'			=> '/base/CFieldTag.php',
		'IBaseUser'			=> '/security/IBaseUser.php',
		'PDOConnection'		=> '/data/PDOConnection.php',
		'CDataModel'		=> '/data/CDataModel.php',
		'CWhereCondition'	=> '/data/CWhereCondition.php',
		'CDBTag'			=> '/data/CDBTag.php',
		'CHtml'				=> '/web/CHtml.php',
		'CAjaxModel'		=> '/web/CAjaxModel.php',
		'EDialogType'		=> '/web/EDialogType.php',
		'CAjaxJavaScript'	=> '/web/CAjaxJavaScript.php',
		'CAjax'				=> '/web/CAjax.php',
		'TypeControl'		=> '/web/TypeControl.php',
		'MCombo'			=> '/web/MCombo.php',
		'CValidTag'			=> '/validation/CValidTag.php',
		'CMaskTag'			=> '/validation/CMaskTag.php',
		'CValidator'		=> '/validation/CValidator.php',
		'CValidatorFactory' => '/validation/CValidatorFactory.php',
		'Text'				=> '/util/Text.php',
		'Date'				=> '/util/Date.php'
	);
	
}

spl_autoload_register(array('App','autoload'));

